package com.wsl.HealthChallenge.controllers;

import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;

import javax.jdo.JDOHelper;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wsl.HealthChallenge.models.ContestEntry;
import com.wsl.HealthChallenge.models.UserStats;
import com.wsl.HealthChallenge.utils.DataStorageUtils;

/**
 * 
 * Handles requests to view or sign up for a challenge:
 * 
 * @author mark
 */
@Controller
public class TestGoogleHealthController {
    @RequestMapping("/{challengeId}/ghealth")
    public ModelAndView handleRequest(@PathVariable String challengeId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Check if the challenge exists.
        long start = System.currentTimeMillis();

        ContestEntry challenge = DataStorageUtils.getContest(challengeId);
        if (challenge == null) {
            response.getWriter().println("Challenge does not exist.");
            return null;
        }
        PrintWriter writer = response.getWriter();
        writer.println("Challenge ms: " + (System.currentTimeMillis() - start));

        ServletContext servletContext = request.getSession().getServletContext();
        GoogleHealthCalorieRequester requester = new GoogleHealthCalorieRequester(servletContext);

        Map<String, UserStats> allUserStats = challenge.getUserStats();
        for (Entry<String, UserStats> entry : allUserStats.entrySet()) {
            UserStats userStats = entry.getValue();
            int calories = requester.getTrackerValue(request, response,
                    userStats.getGoogleHealthSessionToken(),
                    challenge.getType().googleHealthTracker,
                    challenge.getStartDate(),
                    challenge.getEndDate());
            userStats.setScore(calories);
        }

        JDOHelper.makeDirty(challenge, "userStats");
        long startinsert = System.currentTimeMillis();
        DataStorageUtils.insertOrUpdateContest(challenge);
        writer.println("insertOrUpdate ms: " + (System.currentTimeMillis() - startinsert));

        writer.println("done ms: " + (System.currentTimeMillis() - start));
        //response.getWriter().println("Challenge exist.");
        return null;
    }
}